package com.siyoumi.app.sys.service.web_oauth;

import com.siyoumi.app.sys.service.WxApiService;
import com.siyoumi.app.sys.vo.WebOauthCallBackData;
import com.siyoumi.app.sys.vo.WebOauthVo;
import com.siyoumi.app.sys.vo.LoginVo;
import com.siyoumi.component.XBean;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;

//公众号
@Slf4j
public class WebOauthWx
        extends WebOauth {
    @Override
    public String reHandle(WebOauthVo data) {
        String callbackUrl = getCallbackUrl(data);
        if (isDebug(data)) {
            return callbackUrl;
        }

        SysAccsuperConfig config = XHttpContext.getXConfig();
        String url = XStr.concat("https://open.weixin.qq.com/connect/oauth2/authorize?appid="
                , config.getAconfig_app_id()
                , "&redirect_uri=", XStr.urlEnc(callbackUrl)
                , "&response_type=code&scope=", data.getScope()
                , "&state=#wechat_redirect");
        return url;
    }

    @Override
    public WebOauthCallBackData callbackHandleToken(WebOauthVo data) {
        WxApiService appWx = WxApiService.getBean("wx");

        LoginVo vo = new LoginVo();
        XBean.copyProperties(data, vo);
        XReturn r = appWx.login(vo);
        log.debug(XJson.toJSONString(r));
        if (r.err()) {
            XValidator.err(r);
        }

        String jwtToken = r.getData("token");
        String openid = r.getData("openid");
        String webToken = getWebToken(jwtToken);

        return WebOauthCallBackData.getIns(openid, webToken);
    }
}
